package org.hepeng.commons.spring.cloud.netflix.zuul;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableDefault;
import com.netflix.zuul.context.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;

/**
 * @author he peng
 */
public class RequestContextHelper {

    private final static HystrixRequestVariableDefault<RequestContext> HYSTRIX_REQUEST_VARIABLE = new HystrixRequestVariableDefault();

    public static void set(RequestContext context) {
        HYSTRIX_REQUEST_VARIABLE.set(context);
    }

    public static RequestContext remove() {
        RequestContext context = HYSTRIX_REQUEST_VARIABLE.get();
        HYSTRIX_REQUEST_VARIABLE.remove();
        return context;
    }

    public static RequestContext get() {
        RequestContext context = RequestContext.getCurrentContext();
        if (context.isEmpty()) {
            RequestContext context1 = HYSTRIX_REQUEST_VARIABLE.get();
            if (Objects.nonNull(context1) && ! context1.isEmpty()) {
                context = context1;
            }
        }
        return context;
    }

    public static Object getServiceId() {
        RequestContext ctx = get();
        Object serviceId = ctx.get(SERVICE_ID_KEY);
        if (Objects.isNull(serviceId)) {
            serviceId = ctx.get(PROXY_KEY);
        }
        return serviceId;
    }

    public static HttpServletRequest getServletRequest() {
         return get().getRequest();
    }

    public static HttpServletResponse getServletResponse() {
        return get().getResponse();
    }


    public static Object getLoadBalancer() {
        return get().get(LOAD_BALANCER_KEY);
    }

    public static Object getRoutePath() {
        return get().get(REQUEST_URI_KEY);
    }
}
